﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace NDF.XnaLibrary.Models
{
	public class AnimationFrame : IComparable
	{
		/// <summary>
		/// Creates a new AnimationFrame object.
		/// </summary>
		/// <param name="time">The time at which the frame is used.</param>
		/// <param name="frames">The collection of BoneTransformations defining this frame.</param>
		public AnimationFrame(TimeSpan time, List<BoneTransformation> frames)
		{
			Time = time;
			BoneTransformations = frames;
		}

		/// <summary>
		/// Gets the time at which this frame is used.
		/// </summary>
		public TimeSpan Time { get; private set; }

		/// <summary>
		/// Gets the BoneTransformations defining this frame.
		/// </summary>
		public List<BoneTransformation> BoneTransformations { get; private set;	}

		/// <summary>
		/// Compares the current instance to another instance of AnimationFrame.
		/// </summary>
		/// <param name="obj">The second frame.</param>
		public int CompareTo(object obj)
		{
			AnimationFrame frame2 = obj as AnimationFrame;

			if (this.Time < frame2.Time)
				return -1;
			else if (this.Time > frame2.Time)
				return 1;
			else 
				return 0;
		}

		/// <summary>
		/// Gets a matrix array containing all the transformations in the this frame.
		/// </summary>
		/// <param name="modelInfo"></param>
		/// <returns></returns>
		public Matrix[] GetFullModelBoneTransformations(SkinnedModelInfo modelInfo)
		{
			Matrix[] fullModelBones = new Matrix[modelInfo.BindPose.Count];
			modelInfo.BindPose.CopyTo(fullModelBones);

			foreach (BoneTransformation bone in this.BoneTransformations)
			{
				int boneIndex = modelInfo.SkeletonIndices[bone.Bone];
				fullModelBones[boneIndex] *= bone.Transform;
			}

			return fullModelBones;
		}
	}
}
